package com.ssm.sport.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ssm.sport.entity.User;
import com.ssm.sport.mapper.UserMapper;
import com.ssm.sport.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

/**
 * 用户服务实现类
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Override
    public User login(String username, String password) {
        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            return null;
        }

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        User user = baseMapper.selectOne(queryWrapper);
        
        if (user != null && user.getStatus() == 1) {
            // 验证密码
            String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
            if (md5Password.equals(user.getPassword())) {
                user.setPassword(null);  // 清空密码
                return user;
            }
        }
        
        return null;
    }

    @Override
    public boolean register(User user) {
        if (user == null 
            || StringUtils.isBlank(user.getUsername()) 
            || StringUtils.isBlank(user.getPassword())) {
            return false;
        }
        
        // 检查用户名是否已存在
        if (checkUsername(user.getUsername())) {
            return false;
        }
        
        // 密码MD5加密
        String md5Password = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        user.setPassword(md5Password);
        
        // 设置用户状态为正常
        user.setStatus(1);
        
        return baseMapper.insert(user) > 0;
    }

    @Override
    public boolean checkUsername(String username) {
        if (StringUtils.isBlank(username)) {
            return false;
        }
        
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", username);
        
        return baseMapper.selectCount(queryWrapper) > 0;
    }
    
    @Override
    public User getByPhone(String phone) {
        if (StringUtils.isBlank(phone)) {
            return null;
        }
        
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", phone);
        
        return baseMapper.selectOne(queryWrapper);
    }
} 